<?php

namespace App\Http\Middleware;

use App\Jobs\OperationLog;
use Closure;
use Illuminate\Http\Request;

class OperationLogMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param Request $request
     * @param Closure $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        if (!auth()->user()->status) {
            abort('400', '你的账户已被封禁,不能进行任何操作');
        };

        $response = $next($request);

        $content = $request->all();

        if (array_key_exists('file', $content)) {
            unset($content['file']);
        }

        $operation = array(
            'user_id' => auth('api')->id(),
            'path' => $request->path(),
            'method' => $request->method(),
            'ip' => $request->ip(),
            'describe' => config('routes_name')[$request->route()->getName()],
            'content' => $content,
        );

        // 如果请求方式不是get 就分发任务
        OperationLog::dispatchIf($request->method() != 'GET', $operation);

        return $response;
    }
}
